package org.yjc.controller;

import java.util.HashMap;
import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.yjc.custom.DatagridUtils;
import org.yjc.entity.Journal;
import org.yjc.service.JournalService;

@Controller
@RequestMapping(value="/journal")
public class JournalController {
	@Autowired
	private JournalService journalservice;
	
	@RequestMapping(value="/journalmain")
	public String jurnalmain() {
		return "journal/journalmain";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object journallist(DatagridUtils param,String handlename,String handleuser,String handle) {
		Pageable pageable = param.buildPageable1();
		Page<Journal> page = null;
		//安全查询
		Specification<Journal> spec = new Specification<Journal>() {
			@Override
			public Predicate toPredicate(Root<Journal> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				if(StringUtils.hasText(handlename)) {
					rules.add(criteriaBuilder.like(root.get("handlename"), "%"+handlename+"%"));
				}else if(StringUtils.hasText(handleuser)) {
					rules.add(criteriaBuilder.like(root.get("handleuser"), "%"+handleuser+"%"));
				}else if(StringUtils.hasText(handle)) {
					rules.add(criteriaBuilder.like(root.get("handle"), "%"+handle+"%"));
				}
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		page = journalservice.findAll(spec,pageable);
		HashMap<String, Object> result = DatagridUtils.biuldDatagridResult(page);
		return result;
	}
}
